<script setup>
import { ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { logout as logoutApi } from './api/auth'
import Navigation from './components/Navigation.vue'
import StudentManagement from './components/StudentManagement.vue'
import TeacherManagement from './components/TeacherManagement.vue'
import ClazzManagement from './components/ClazzManagement.vue'
import Login from './components/Login.vue'
import StudentHome from './components/StudentHome.vue'
import StudentProfile from './components/StudentProfile.vue'
import StudentSchedule from './components/StudentSchedule.vue'
import StudentCourse from './components/StudentCourse.vue'
import StudentGrades from './components/StudentGrades.vue'
import StudentReminders from './components/StudentReminders.vue'
import StudentNotices from './components/StudentNotices.vue'
import StudentRequest from './components/StudentRequest.vue'
import TeacherHome from './components/TeacherHome.vue'
import TeacherProfile from './components/TeacherProfile.vue'
import TeacherSchedule from './components/TeacherSchedule.vue'
import TeacherTodayCourses from './components/TeacherTodayCourses.vue'
import TeacherGradeManagement from './components/TeacherGradeManagement.vue'
import TeacherWorkload from './components/TeacherWorkload.vue'
import TeacherStudentManagement from './components/TeacherStudentManagement.vue'
import TeacherMyRequest from './components/TeacherMyRequest.vue'
import TeacherCourseReview from './components/TeacherCourseReview.vue'
import AdminHome from './components/AdminHome.vue'
import AdminProfile from './components/AdminProfile.vue'
import AdminManagement from './components/AdminManagement.vue'
import AdminRequestManagement from './components/AdminRequestManagement.vue'
import AdminNoticeManagement from './components/AdminNoticeManagement.vue'
import TeacherNoticeManagement from './components/TeacherNoticeManagement.vue'
import CourseManagement from './components/CourseManagement.vue'
import ClassroomManagement from './components/ClassroomManagement.vue'
import ScheduleManagement from './components/ScheduleManagement.vue'
import ScheduleStatistics from './components/ScheduleStatistics.vue'

// 当前页面状态
const currentPage = ref('student')
const isAuthed = ref(false) // 默认显示登录页面
const role = ref('')

// 页面切换处理
const handlePageChange = (page) => {
  console.log('App.vue 收到页面切换事件:', page)
  currentPage.value = page
  console.log('当前页面已更新为:', currentPage.value)
}

const handleLoginSuccess = () => {
  isAuthed.value = true
  role.value = localStorage.getItem('role') || ''
  // 登录成功后根据角色进入不同页面
  if (role.value === 'teacher') {
    currentPage.value = 'teacher-home'
  } else if (role.value === 'admin') {
    // 管理员直接登录到管理员首页
    currentPage.value = 'admin-home'
  } else {
    currentPage.value = 'student-home'
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '退出后需要重新登录才能访问系统',
      '确认要退出登录吗？',
      {
        confirmButtonText: '确认退出',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        customClass: 'logout-confirm-box'
      }
    )
    
    // 尝试调用后端退出登录接口（记录日志），完全静默处理
    try {
      const userInfo = localStorage.getItem('user')
      const currentRole = localStorage.getItem('role')
      let userId = null
      
      if (userInfo) {
        try {
          const user = JSON.parse(userInfo)
          // 根据不同角色获取不同的ID字段
          if (currentRole === 'student') {
            userId = user.stuId || user.stuNo
          } else if (currentRole === 'teacher') {
            userId = user.teId || user.teNo
          } else if (currentRole === 'admin') {
            userId = user.adminId || user.adminNo
          }
        } catch (e) {
          // 静默处理
        }
      }
      
      // 尝试调用后端接口，但完全静默处理错误
      logoutApi({
        userId: userId?.toString(),
        role: currentRole
      }).catch(() => {
        // 完全静默，不输出任何信息
      })
    } catch (e) {
      // 完全静默
    }
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('role')
    role.value = ''
    isAuthed.value = false
    currentPage.value = 'student' // 退出后回到登录页面
    
    ElMessage({
      type: 'success',
      message: '已安全退出登录',
      duration: 2000
    })
  } catch (error) {
    // 用户点击取消或关闭对话框，不做任何操作
    if (error !== 'cancel') {
      console.log('退出登录已取消')
    }
  }
}
</script>

<template>
  <div id="app" class="layout">
    <template v-if="!isAuthed">
      <main class="content content--full">
        <Login @login-success="handleLoginSuccess" />
      </main>
    </template>
    <template v-else>
      <aside class="sidebar">
        <Navigation
          v-model:current-page="currentPage"
          :role="role"
          @page-change="handlePageChange"
          @logout="handleLogout"
        />
      </aside>

      <main class="content">
        <StudentHome v-if="currentPage === 'student-home' && role === 'student'" @page-change="handlePageChange" />
        <StudentProfile v-if="currentPage === 'student-profile' && role === 'student'" />
        <StudentSchedule v-if="currentPage === 'student-schedule' && role === 'student'" />
        <StudentCourse v-if="currentPage === 'student-course' && role === 'student'" />
        <StudentGrades v-if="currentPage === 'student-grades' && role === 'student'" />
        <StudentReminders v-if="currentPage === 'student-reminders' && role === 'student'" />
        <StudentNotices v-if="currentPage === 'student-notices' && role === 'student'" />
        <StudentRequest v-if="currentPage === 'student-request' && role === 'student'" />
        <TeacherHome v-if="currentPage === 'teacher-home' && role === 'teacher'" @page-change="handlePageChange" />
        <TeacherProfile v-if="currentPage === 'teacher-profile' && role === 'teacher'" />
        <TeacherSchedule v-if="currentPage === 'teacher-schedule' && role === 'teacher'" />
        <TeacherTodayCourses v-if="currentPage === 'teacher-today-courses' && role === 'teacher'" />
        <TeacherGradeManagement v-if="currentPage === 'teacher-grade' && role === 'teacher'" />
        <TeacherWorkload v-if="currentPage === 'teacher-workload' && role === 'teacher'" />
        <TeacherStudentManagement v-if="currentPage === 'teacher-students' && role === 'teacher'" />
        <TeacherMyRequest v-if="currentPage === 'teacher-my-request' && role === 'teacher'" />
        <TeacherCourseReview v-if="currentPage === 'teacher-course-review' && role === 'teacher'" />
        <TeacherNoticeManagement v-if="currentPage === 'teacher-notice' && role === 'teacher'" />
                <AdminHome v-if="currentPage === 'admin-home' && role === 'admin'" @change-page="handlePageChange" />
                <AdminProfile v-if="currentPage === 'admin-profile' && role === 'admin'" />
                <StudentManagement v-if="currentPage === 'student' && role === 'admin'" />
                <TeacherManagement v-if="currentPage === 'teacher' && role === 'admin'" />
                <ClazzManagement v-if="currentPage === 'clazz' && role === 'admin'" />
                <CourseManagement v-if="currentPage === 'course' && role === 'admin'" />
                <ClassroomManagement v-if="currentPage === 'classroom' && role === 'admin'" />
                <ScheduleManagement v-if="currentPage === 'schedule' && role === 'admin'" />
                <ScheduleStatistics v-if="currentPage === 'schedule-statistics' && role === 'admin'" />
                <AdminManagement v-if="currentPage === 'admin' && role === 'admin'" />
                <AdminRequestManagement v-if="currentPage === 'admin-request' && role === 'admin'" />
                <AdminNoticeManagement v-if="currentPage === 'admin-notice' && role === 'admin'" />
      </main>
    </template>
  </div>
</template>

<style>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

html, body {
  height: 100%;
  font-family: 'PingFang SC', 'Microsoft YaHei', 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: #f5f7fa;
}

#app.layout {
  display: grid;
  grid-template-columns: 260px 1fr;
  grid-template-rows: 100vh;
  overflow: hidden;
  color: #2c3e50;
}

.sidebar {
  height: 100vh;
  overflow: hidden;
  background: transparent;
  box-shadow: 18px 0 60px -42px rgba(23, 30, 70, 0.55);
}

.content {
  position: relative;
  height: 100vh;
  overflow: auto;
  padding: 32px;
  background: linear-gradient(180deg, rgba(246, 248, 254, 0.94) 0%, rgba(240, 244, 255, 0.9) 100%);
}

.content::before {
  content: "";
  position: absolute;
  top: 40px;
  right: 60px;
  width: 320px;
  height: 320px;
  background: radial-gradient(circle, rgba(118, 75, 162, 0.14) 0%, transparent 70%);
  filter: blur(12px);
  pointer-events: none;
}

.content::after {
  content: "";
  position: absolute;
  bottom: 60px;
  left: 40px;
  width: 380px;
  height: 380px;
  background: radial-gradient(circle, rgba(102, 126, 234, 0.14) 0%, transparent 70%);
  filter: blur(16px);
  pointer-events: none;
}

.content > * {
  position: relative;
  z-index: 1;
}

.content.content--full {
  grid-column: 1 / -1;
  padding: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 隐藏全局滚动条，但保留功能区滚动（仅 content 内部可滚动）*/
html, body {
  overflow: hidden;
}

/* Element Plus 全局样式优化 */
.el-message {
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15) !important;
  border: none !important;
}

.el-message-box {
  border-radius: 16px !important;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15) !important;
  border: none !important;
}

.el-message-box__header {
  background: #f5f7fa !important;
  border-radius: 8px 8px 0 0 !important;
  padding: 16px 20px !important;
  border-bottom: 1px solid #ebeef5 !important;
}

.el-message-box__title {
  color: #2c3e50 !important;
  font-weight: 600 !important;
  font-size: 18px !important;
}

.el-message-box__content {
  padding: 20px !important;
}

.el-message-box__btns {
  padding: 16px 20px !important;
  background: #f5f7fa !important;
  border-radius: 0 0 8px 8px !important;
  border-top: 1px solid #ebeef5 !important;
}

.el-message-box__btns .el-button {
  border-radius: 4px !important;
  font-weight: 500 !important;
  padding: 10px 20px !important;
  transition: all 0.3s ease !important;
}

.el-message-box__btns .el-button--primary {
  background: #409eff !important;
  border-color: #409eff !important;
}

.el-message-box__btns .el-button--primary:hover {
  background: #66b1ff !important;
  border-color: #66b1ff !important;
}

/* 加载动画优化 */
.el-loading-mask {
  background: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(4px) !important;
}

.el-loading-spinner {
  color: #409eff !important;
}

/* 表格加载状态优化 */
.el-table__empty-block {
  background: #f5f7fa !important;
  border-radius: 8px !important;
  margin: 16px !important;
}

.el-table__empty-text {
  color: #6c757d !important;
  font-size: 16px !important;
  font-weight: 500 !important;
}

/* 退出登录确认对话框优化 */
.logout-confirm-box {
  border-radius: 16px !important;
  padding: 20px !important;
}

.logout-confirm-box .el-message-box__header {
  padding-bottom: 16px !important;
}

.logout-confirm-box .el-message-box__title {
  font-size: 20px !important;
  font-weight: 600 !important;
  color: #e6a23c !important;
}

.logout-confirm-box .el-message-box__content {
  padding: 20px 0 !important;
  font-size: 15px !important;
  color: #606266 !important;
  line-height: 1.6 !important;
}

.logout-confirm-box .el-message-box__btns {
  padding-top: 20px !important;
}

.logout-confirm-box .el-button {
  padding: 12px 24px !important;
  font-size: 14px !important;
  border-radius: 8px !important;
  font-weight: 500 !important;
}

.logout-confirm-box .el-button--default {
  background: #f5f7fa !important;
  border-color: #dcdfe6 !important;
  color: #606266 !important;
}

.logout-confirm-box .el-button--default:hover {
  background: #ecf5ff !important;
  border-color: #409eff !important;
  color: #409eff !important;
}

.logout-confirm-box .el-button--primary {
  background: #e6a23c !important;
  border-color: #e6a23c !important;
}

.logout-confirm-box .el-button--primary:hover {
  background: #ebb563 !important;
  border-color: #ebb563 !important;
}
</style>
